import { buttonProps } from "@/components/GlobalButton/interface";
import { ColumnProps } from "@/components/ProTable/interface";
import { ProTableValue } from "@/interface/public";

/**
 * @name 表格新增
 * @param { ColumnProps[]}columns 表格列
 * @param {ProTableValue} proTableBox 表格的 ref
 * @param {Object} form 新增的数据
 * @param {string} dictStr 数据字典字段
 */
export const useTableAdd = (
  columns: ColumnProps[],
  proTableBox: ProTableValue,
  form: Object = {},
  submit: () => Promise<void>,
  init?: Function,
  dictStr?: string
) => {
  const addForm = ref();

  onBeforeMount(() => {
    addForm.value = JSON.parse(
      JSON.stringify({
        ...form,
        isAddFlag: "true",
        edit: ""
      })
    );
    initForm(addForm.value);
  });

  const keyupSubmit = (e: KeyboardEvent) => {
    if (e.key === "Enter" && isAddFlag.value) {
      submit();
    }
  };

  onMounted(() => {
    window.addEventListener("keydown", keyupSubmit, false);
  });

  onBeforeUnmount(() => {
    window.removeEventListener("keydown", keyupSubmit, false);
  });

  /**
   * @description: 初始化
   * @param {any} form
   * @return {*}
   */
  const initForm = async (form: any) => {
    // 获取初始参数
    if (typeof init === "function") {
      const params = (await init()) || {};
      Object.assign(form, params);
    }
  };

  // 字典可选项
  let dictOp = ref();

  /**
   * @description: 是否编辑状态
   * @param {*} computed
   * @return {*}
   */
  const isAddFlag = computed(() => {
    let flag = false;
    if (proTableBox.value) {
      flag = typeof proTableBox.value.tableData.find(v => v.isAddFlag || v["edit"]) !== "undefined";
    }

    return flag;
  });
  // 新增必填字段
  const requiredField = computed(() => columns.filter(item => item.required));

  /**
   * @description: 新增一条空数据
   * @return {*}
   */
  const add = async (db?: Function) => {
    await setDictValue();
    if (isAddFlag.value) return elMessage("请先完成当前操作", "warning");
    if (proTableBox.value) {
      const params = {
        ...addForm.value,
        ...dictOp.value
      };

      proTableBox.value.tableData.unshift(JSON.parse(JSON.stringify(params)));

      db && db();
    }
  };

  /**
   * @param {Object} row 复制的数据
   * @param {number} index 复制数据的下标
   * @param {string} retainField 复制时需要回填的字段
   * @description 复制数据新增
   */
  const copyAdd = async (row: Object = {}, retainField = "") => {
    if (isAddFlag.value) return elMessage("请先完成当前操作", "warning");

    const newRow = JSON.parse(JSON.stringify(row));
    await initForm(newRow);
    await setDictValue(newRow);

    Object.assign(newRow, {
      id: "",
      douser: ""
    });

    // 清除不需要保留字段
    const fields = retainField.split(",");
    Object.keys(row).forEach(key => {
      if (!fields.includes(key)) {
        newRow[key] = "";
      }
    });

    if (proTableBox.value) {
      newRow.isAddFlag = "true";
      proTableBox.value.tableData.unshift(newRow);
    }
  };

  /**
   * @param {Object} row 编辑的数据
   * @param {number} index 编辑数据的下标
   * @param {string} emptyField 复制时不需要回填的字段
   * @description 复制数据新增
   */
  const edit = async (row: any) => {
    initForm(row);
    row.douser = "";
    await setDictValue();
    Object.assign(row, {
      isAddFlag: "true",
      ...dictOp.value
    });
  };

  /**
   * @param {string} code 数据字典字段
   * @description 将数据字典内容设置到指定字段
   */
  const setDictValue = async (row?: any) => {
    if (!dictStr) return;
    // 数据字典内容
    const data = await dictionaryListByCodes({ code: dictStr || "" });
    dictOp.value = {};
    for (let item of data) {
      const { key, value } = item || {};
      const arr = changeArrField(value, "dvalue", "dvalue");
      dictOp.value[key + "Op"] = arr;
    }

    if (row) {
      Object.assign(row, dictOp.value);
    }
  };

  /**
   * @description: 表格基础按钮
   * @return {*}
   */
  const tableBasicBtn = (copyAddStr: string = "", isEdit: (row: any) => boolean): buttonProps[] => {
    return [
      {
        label: "",
        type: "primary",
        hide: (row: any) => row?.isAddFlag !== "true" && !row["edit"],
        icon: "svg-copyAdd",
        tooltip: "复制新增",
        attrs: {
          link: true
        },
        methods: (row: any) => copyAdd(row, copyAddStr)
      },
      {
        label: "",
        type: "primary",
        tooltip: "编辑",
        hide: (row: any) => row?.isAddFlag !== "true" && !row["edit"] && isEdit && isEdit(row),
        icon: "svg-edit",
        attrs: {
          link: true
        },
        methods: (row: any) => edit(row)
      },
      {
        label: "",
        type: "primary",
        tooltip: "完成",
        icon: "svg-accomplish",
        hide: (row: any) => row?.isAddFlag === "true" || row["edit"],
        methods: async () => submit(),
        attrs: {
          link: true
        }
      },
      {
        label: "",
        tooltip: "取消",
        type: "danger",
        icon: "svg-cancel",
        attrs: {
          link: true
        },
        hide: (row: any) => row?.isAddFlag === "true" || row["edit"],
        methods: () => proTableBox.value?.getTableList()
      }
    ];
  };

  return {
    isAddFlag,
    requiredField,
    add,
    copyAdd,
    edit,
    setDictValue,
    tableBasicBtn
  };
};
